import React, { useState, useEffect, useCallback } from "react";
import {
  Card,
  List,
  Badge,
  Button,
  Tag,
  Typography,
  Space,
  Tabs,
  Empty,
  Modal,
  Checkbox,
  Dropdown,
  Menu,
  Input,
  Select,
  message,
  Spin,
  Tooltip,
  Divider,
} from "antd";
import {
  BellOutlined,
  DeleteOutlined,
  CheckOutlined,
  ExclamationCircleOutlined,
  MoreOutlined,
  SearchOutlined,
  FilterOutlined,
  ReloadOutlined,
  SettingOutlined,
  BulbOutlined,
} from "@ant-design/icons";
import { useAuth } from "../../contexts/AuthContext";
import { useWebSocket } from "../../contexts/WebSocketContext";
import {
  notificationApi,
  NotificationRequest,
  NotificationStats,
} from "../../services/notificationService";
import moment from "moment";
import "./NotificationCenter.less";

const { Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { Search } = Input;
const { Option } = Select;

// 通知类型
export interface Notification {
  id: number;
  userId: number;
  type: string;
  title: string;
  content: string;
  priority: number;
  sourceId?: number;
  sourceType?: string;
  isRead: number;
  aiSuggestion?: string;
  actionUrl?: string;
  createTime: string;
  updateTime: string;
}

const NotificationCenter: React.FC = () => {
  const { state: authState } = useAuth();
  const { state: wsState } = useWebSocket();

  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState("all");
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [stats, setStats] = useState<NotificationStats>({
    total: 0,
    unread: 0,
    system: 0,
    task: 0,
    exam: 0,
    assignment: 0,
    approval: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState("");
  const [filterType, setFilterType] = useState<string | undefined>(undefined);
  const [filterPriority, setFilterPriority] = useState<number | undefined>(
    undefined
  );
  const [settingsVisible, setSettingsVisible] = useState(false);
  const [aiSuggestionLoading, setAiSuggestionLoading] = useState<number | null>(
    null
  );

  // 监听新通知事件
  useEffect(() => {
    const handleNewNotification = (event: CustomEvent) => {
      const newNotification = event.detail;
      setNotifications((prev) => [newNotification, ...prev]);
      loadStats();
    };

    window.addEventListener(
      "newNotification",
      handleNewNotification as EventListener
    );
    return () =>
      window.removeEventListener(
        "newNotification",
        handleNewNotification as EventListener
      );
  }, []);

  useEffect(() => {
    loadNotifications();
    loadStats();
  }, [activeTab, searchKeyword, filterType, filterPriority]);

  // 加载通知列表
  const loadNotifications = async () => {
    try {
      setLoading(true);

      const params: NotificationRequest = {
        page: 1,
        size: 50,
      };

      if (activeTab !== "all") {
        if (activeTab === "unread") {
          params.isRead = 0;
        } else {
          params.type = activeTab;
        }
      }

      if (searchKeyword) {
        params.keyword = searchKeyword;
      }

      if (filterType) {
        params.type = filterType;
      }

      if (filterPriority) {
        params.priority = filterPriority;
      }

      const result = await notificationApi.getNotifications(params);

      if (result.code === 0) {
        setNotifications(result.data.list || result.data);
        console.log("✅ 通知数据加载成功", result.data);
      } else {
        message.error(result.message || "加载通知失败");
      }
    } catch (error: any) {
      console.error("❌ 加载通知失败:", error);
      message.error(error.message || "加载通知失败");
    } finally {
      setLoading(false);
    }
  };

  // 加载统计信息
  const loadStats = async () => {
    try {
      const result = await notificationApi.getStats();
      if (result.code === 0) {
        setStats(result.data);
        console.log("✅ 统计数据加载成功", result.data);
      }
    } catch (error) {
      console.error("❌ 获取通知统计失败:", error);
    }
  };

  // 标记为已读
  const markAsRead = async (ids: number[]) => {
    try {
      const result = await notificationApi.markAsRead(ids);
      if (result.code === 0) {
        setNotifications((prev) =>
          prev.map((notif) =>
            ids.includes(notif.id) ? { ...notif, isRead: 1 } : notif
          )
        );
        message.success("已标记为已读");
        loadStats();
      } else {
        message.error(result.message || "标记已读失败");
      }
    } catch (error: any) {
      console.error("❌ 标记已读失败:", error);
      message.error(error.message || "标记已读失败");
    }
  };

  // 删除通知
  const deleteNotifications = async (ids: number[]) => {
    try {
      const result = await notificationApi.deleteNotifications(ids);
      if (result.code === 0) {
        setNotifications((prev) =>
          prev.filter((notif) => !ids.includes(notif.id))
        );
        setSelectedIds([]);
        message.success("删除成功");
        loadStats();
      } else {
        message.error(result.message || "删除失败");
      }
    } catch (error: any) {
      console.error("❌ 删除失败:", error);
      message.error(error.message || "删除失败");
    }
  };

  // 生成AI建议
  const generateAISuggestion = async (notificationId: number) => {
    try {
      setAiSuggestionLoading(notificationId);
      const result = await notificationApi.generateAISuggestion(notificationId);

      if (result.code === 0) {
        setNotifications((prev) =>
          prev.map((notif) =>
            notif.id === notificationId
              ? { ...notif, aiSuggestion: result.data.suggestion }
              : notif
          )
        );
        message.success("AI建议生成成功");
      } else {
        message.error(result.message || "生成AI建议失败");
      }
    } catch (error: any) {
      console.error("❌ 生成AI建议失败:", error);
      message.error(error.message || "生成AI建议失败");
    } finally {
      setAiSuggestionLoading(null);
    }
  };

  // 批量操作
  const handleBatchOperation = (operation: string) => {
    if (selectedIds.length === 0) {
      message.warning("请先选择通知");
      return;
    }

    switch (operation) {
      case "read":
        markAsRead(selectedIds);
        break;
      case "delete":
        Modal.confirm({
          title: "确认删除",
          content: `确定要删除选中的 ${selectedIds.length} 条通知吗？`,
          onOk: () => deleteNotifications(selectedIds),
        });
        break;
    }
  };

  // 处理通知点击
  const handleNotificationClick = (notification: Notification) => {
    // 标记为已读
    if (notification.isRead === 0) {
      markAsRead([notification.id]);
    }

    // 跳转到相关页面
    if (notification.actionUrl) {
      // 这里应该使用路由跳转
      // history.push(notification.actionUrl);
      console.log("跳转到:", notification.actionUrl);
    }
  };

  // 获取通知类型标签
  const getTypeTag = (type: string) => {
    const typeMap: { [key: string]: { text: string; color: string } } = {
      system: { text: "系统", color: "blue" },
      task: { text: "任务", color: "orange" },
      exam: { text: "考试", color: "red" },
      assignment: { text: "作业", color: "green" },
      approval: { text: "审批", color: "purple" },
    };

    const config = typeMap[type] || { text: "其他", color: "default" };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取优先级标签
  const getPriorityTag = (priority: number) => {
    const priorityMap: { [key: number]: { text: string; color: string } } = {
      1: { text: "低", color: "green" },
      2: { text: "中", color: "blue" },
      3: { text: "高", color: "orange" },
      4: { text: "紧急", color: "red" },
    };

    const config = priorityMap[priority] || { text: "普通", color: "default" };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 渲染通知项
  const renderNotificationItem = (notification: Notification) => {
    const isSelected = selectedIds.includes(notification.id);
    const isUnread = notification.isRead === 0;

    return (
      <List.Item
        key={notification.id}
        className={`notification-item ${isUnread ? "unread" : ""} ${isSelected ? "selected" : ""}`}
        actions={[
          <Tooltip title="生成AI建议">
            <Button
              type="text"
              icon={<BulbOutlined />}
              loading={aiSuggestionLoading === notification.id}
              onClick={(e) => {
                e.stopPropagation();
                generateAISuggestion(notification.id);
              }}
            />
          </Tooltip>,
          <Tooltip title={isUnread ? "标记已读" : "已读"}>
            <Button
              type="text"
              icon={<CheckOutlined />}
              disabled={!isUnread}
              onClick={(e) => {
                e.stopPropagation();
                markAsRead([notification.id]);
              }}
            />
          </Tooltip>,
          <Tooltip title="删除">
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                deleteNotifications([notification.id]);
              }}
            />
          </Tooltip>,
        ]}
        onClick={() => handleNotificationClick(notification)}
      >
        <div className="notification-content">
          <div className="notification-header">
            <Checkbox
              checked={isSelected}
              onChange={(e) => {
                e.stopPropagation();
                if (e.target.checked) {
                  setSelectedIds((prev) => [...prev, notification.id]);
                } else {
                  setSelectedIds((prev) =>
                    prev.filter((id) => id !== notification.id)
                  );
                }
              }}
              onClick={(e) => e.stopPropagation()}
            />
            <Space style={{ marginLeft: 8 }}>
              {getTypeTag(notification.type)}
              {getPriorityTag(notification.priority)}
              {isUnread && <Badge status="processing" />}
            </Space>
            <Text type="secondary" style={{ marginLeft: "auto" }}>
              {moment(notification.createTime).fromNow()}
            </Text>
          </div>

          <div className="notification-body">
            <Text strong className="notification-title">
              {notification.title}
            </Text>
            <Paragraph className="notification-text" ellipsis={{ rows: 2 }}>
              {notification.content}
            </Paragraph>

            {notification.aiSuggestion && (
              <div className="ai-suggestion">
                <BulbOutlined style={{ color: "#1890ff", marginRight: 4 }} />
                <Text type="secondary">{notification.aiSuggestion}</Text>
              </div>
            )}
          </div>
        </div>
      </List.Item>
    );
  };

  // 批量操作菜单
  const batchMenuItems = (
    <Menu onClick={({ key }) => handleBatchOperation(key)}>
      <Menu.Item key="read" icon={<CheckOutlined />}>
        标记已读
      </Menu.Item>
      <Menu.Item key="delete" icon={<DeleteOutlined />} danger>
        批量删除
      </Menu.Item>
    </Menu>
  );

  // 过滤菜单
  const filterMenuItems = (
    <Menu>
      <Menu.SubMenu key="type" title="按类型筛选">
        <Menu.Item key="all-types" onClick={() => setFilterType(undefined)}>
          全部类型
        </Menu.Item>
        <Menu.Item key="system" onClick={() => setFilterType("system")}>
          系统通知
        </Menu.Item>
        <Menu.Item key="task" onClick={() => setFilterType("task")}>
          任务通知
        </Menu.Item>
        <Menu.Item key="exam" onClick={() => setFilterType("exam")}>
          考试通知
        </Menu.Item>
        <Menu.Item key="assignment" onClick={() => setFilterType("assignment")}>
          作业通知
        </Menu.Item>
      </Menu.SubMenu>
      <Menu.SubMenu key="priority" title="按优先级筛选">
        <Menu.Item
          key="all-priorities"
          onClick={() => setFilterPriority(undefined)}
        >
          全部优先级
        </Menu.Item>
        <Menu.Item key="priority-4" onClick={() => setFilterPriority(4)}>
          紧急
        </Menu.Item>
        <Menu.Item key="priority-3" onClick={() => setFilterPriority(3)}>
          高
        </Menu.Item>
        <Menu.Item key="priority-2" onClick={() => setFilterPriority(2)}>
          中
        </Menu.Item>
        <Menu.Item key="priority-1" onClick={() => setFilterPriority(1)}>
          低
        </Menu.Item>
      </Menu.SubMenu>
    </Menu>
  );

  return (
    <div className="notification-center">
      <Card
        title={
          <div className="notification-header">
            <Space>
              <BellOutlined />
              <span>通知中心</span>
              <Badge count={stats.unread} />
            </Space>
            <Space>
              <Search
                placeholder="搜索通知..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                style={{ width: 200 }}
                allowClear
              />
              <Dropdown overlay={filterMenuItems} trigger={["click"]}>
                <Button icon={<FilterOutlined />}>筛选</Button>
              </Dropdown>
              <Button
                icon={<ReloadOutlined />}
                onClick={() => {
                  loadNotifications();
                  loadStats();
                }}
              >
                刷新
              </Button>
              <Button
                icon={<SettingOutlined />}
                onClick={() => setSettingsVisible(true)}
              >
                设置
              </Button>
            </Space>
          </div>
        }
      >
        {/* 批量操作栏 */}
        {selectedIds.length > 0 && (
          <div className="batch-actions">
            <Space>
              <Text>已选择 {selectedIds.length} 项</Text>
              <Dropdown overlay={batchMenuItems} trigger={["click"]}>
                <Button>批量操作</Button>
              </Dropdown>
              <Button onClick={() => setSelectedIds([])}>取消选择</Button>
            </Space>
            <Divider />
          </div>
        )}

        {/* 通知标签页 */}
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab={`全部 (${stats.total})`} key="all" />
          <TabPane tab={`未读 (${stats.unread})`} key="unread" />
          <TabPane tab={`系统 (${stats.system})`} key="system" />
          <TabPane tab={`任务 (${stats.task})`} key="task" />
          <TabPane tab={`考试 (${stats.exam})`} key="exam" />
          <TabPane tab={`作业 (${stats.assignment})`} key="assignment" />
          <TabPane tab={`审批 (${stats.approval})`} key="approval" />
        </Tabs>

        {/* 通知列表 */}
        <Spin spinning={loading}>
          {notifications.length > 0 ? (
            <List
              dataSource={notifications}
              renderItem={renderNotificationItem}
              pagination={{
                total: stats.total,
                pageSize: 20,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              }}
            />
          ) : (
            <Empty description="暂无通知" />
          )}
        </Spin>
      </Card>

      {/* 通知设置Modal */}
      <Modal
        title="通知设置"
        open={settingsVisible}
        onCancel={() => setSettingsVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setSettingsVisible(false)}>
            取消
          </Button>,
          <Button key="save" type="primary">
            保存设置
          </Button>,
        ]}
      >
        <div className="notification-settings">
          <h4>通知类型设置</h4>
          <Checkbox.Group style={{ width: "100%" }}>
            <Checkbox value="system">系统通知</Checkbox>
            <Checkbox value="task">任务通知</Checkbox>
            <Checkbox value="exam">考试通知</Checkbox>
            <Checkbox value="assignment">作业通知</Checkbox>
          </Checkbox.Group>

          <Divider />

          <h4>推送设置</h4>
          <Checkbox>桌面通知推送</Checkbox>
          <br />
          <Checkbox>邮件通知</Checkbox>
          <br />
          <Checkbox>短信通知（重要）</Checkbox>

          <Divider />

          <h4>AI建议设置</h4>
          <Checkbox>自动生成AI建议</Checkbox>
          <br />
          <Checkbox>智能优先级调整</Checkbox>
        </div>
      </Modal>
    </div>
  );
};

export default NotificationCenter;
